'use strict';
// 分类
const Controller = require('egg').Controller;
class ClassController extends Controller {
    // 创建 修改 分类
    async edit() {
        const { ctx, app } = this
        const { id, title, image_url, sort, status } = ctx.request.body
        ctx.validate({
            title: { type: 'string', required: true, desc: '分类标题' },
            image_url: { type: 'string', required: true, desc: '分类图片路径' },
        })
        console.log(id)
        let list, oneList
        if (id == '' || id == 0 || id == undefined) {  //创建 
            // 标题是否存在
            oneList = await app.model.Class.findOne({
                where: {
                    title
                }
            })
            if (oneList) {
                ctx.throw(400, '标题名已存在')
            }
            list = await app.model.Class.create({
                title, image_url,  sort, status
            })
        } else { //修改
            oneList = await app.model.Class.findByPk(id)
            if (!oneList) {
                ctx.throw(400, '数据不存在')
            }
            list = await oneList.update({
                title, image_url, sort , status
            });
        }
        ctx.apiSuccess(list)
    }
    // 查询 所以 分类
    async list() {
        const { ctx, app } = this
        const {title}=ctx.request.body
        let Op=app.Sequelize.Op;
        let rows = await app.model.Class.findAndCountAll({
            where: {
                title:{
                    [Op.like]:`%${title}%`
                },
                status: '1'
            },
            order: [['sort', 'ASC']]
        })

        ctx.apiSuccess(rows)
    }
    //删除
    async del(){
        const {ctx,app}=this
        const id=ctx.params.id
        const list=await app.model.Class.findByPk(id)
        if(!list){
            ctx.throw(400,'数据不存在')
        }
        list.destroy()
        ctx.apiSuccess('删除成功')
    }
}
module.exports = ClassController;
